package transaction

import (
	"context"
	"fmt"
	"time"

	"gitee.com/liuxuezhan/ar-platform/assets-api/internal/svc"
	"gitee.com/liuxuezhan/ar-platform/assets-api/internal/types"
	"gitee.com/liuxuezhan/ar-platform/base-common/headInfo"
	"gitee.com/liuxuezhan/ar-platform/rpc-client/assetsClient/rpc"
	"github.com/zeromicro/go-zero/core/logx"
)

type TransactionListPageLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

// 用户交易页面--历史记录
func NewTransactionListPageLogic(ctx context.Context, svcCtx *svc.ServiceContext) *TransactionListPageLogic {
	return &TransactionListPageLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *TransactionListPageLogic) TransactionListPage(req *types.TransactionListPageReq) (resp *types.TransactionListPageRes, err error) {
	userId := headInfo.GetTokenUid(l.ctx)

	if req.StartTime > 0 && req.EndTime == 0 {
		startTime := time.Unix(req.StartTime, 0)
		// 获取当天的 23:59:59 时间
		endOfDay := time.Date(startTime.Year(), startTime.Month(), startTime.Day(), 23, 59, 59, 0, startTime.Location())
		req.EndTime = endOfDay.Unix()
	}
	in := rpc.UserWalletLogRequest{
		UserId:    userId,
		Page:      req.Page,
		PageSize:  req.PageSize,
		StartTime: req.StartTime,
		EndTime:   req.EndTime,
		TypeId:    req.TypeId,
	}
	fmt.Printf("@@@@@%v\n", in)
	out, err := l.svcCtx.AssetsRpc.User.UserWalletLog(l.ctx, &in)
	if err != nil {
		return nil, err
	}

	// 响应数据
	resp = &types.TransactionListPageRes{
		Meta: types.TransactionListPage_Meta{
			Total:    out.Meta.Total,
			Page:     out.Meta.Page,
			PageSize: out.Meta.PageSize,
		},
	}
	// 数据映射
	n := len(out.Data)
	resp.Data = make([]types.TransactionListPage_Data, 0, n)
	for i := 0; i < n; i++ {
		data := types.TransactionListPage_Data{
			Id:           out.Data[i].Id,
			Amount:       out.Data[i].Amount,
			BalanceStart: out.Data[i].BalanceStart,
			BalanceEnd:   out.Data[i].BalanceEnd,
			TypeId:       out.Data[i].TypeId,
			TypeName:     out.Data[i].TypeName,
			CreatedAt:    out.Data[i].CreatedAt,
			Remark:       out.Data[i].Description,
		}
		resp.Data = append(resp.Data, data)
	}
	fmt.Printf("@@@@@resp%v\n", resp.Data)

	return
}
